package com.zhgxi.zf.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slave4j.orm.PageData;
import org.slave4j.utils.WebUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;

import com.zhgxi.zf.entity.Dept;
import com.zhgxi.zf.service.DeptService;

@Controller("DeptAction")
public class DeptAction
{
	@Resource
	private DeptService deptService;

	public ModelMap list(HttpServletRequest request)
	{
		PageData<Dept> pageData = new PageData<Dept>();
		//给pageData设置参数
		WebUtils.setPageDataParameter(request, pageData);
		pageData = deptService.find(pageData);

		return new ModelMap(pageData);
	}
	
	public List<Dept> findAll() {
		return deptService.findAllDept();
	}

	public String addForm(Model model)
	{
		return "/zf/dept/input";
	}

	public String editForm(@PathVariable("id") Integer id, Model model)
	{
		Dept dept = deptService.find(id);
		model.addAttribute(dept);
		return "/zf/dept/input";
	}

	public boolean save(Dept dept)
	{
		try {
			if (dept.isNew()||dept.getId() == 0)
			{
				deptService.save(dept);
			} else
			{
				deptService.update(dept);
			}
			return true;
		} catch (RuntimeException e) {
			e.printStackTrace();
			return false;
		}

	}

	public String delete(@PathVariable("id") Integer id)
	{
		deptService.delete(id);
		return "redirect:/zf/dept/list";
	}

	public String visible(@PathVariable("id") Integer id)
	{
		deptService.visible(id);
		return "redirect:/zf/dept/list";
	}

	public String unVisible(@PathVariable("id") Integer id)
	{
		deptService.unVisible(id);
		return "redirect:/zf/dept/list";
	}

	@InitBinder
	public void InitBinder(WebDataBinder dataBinder)
	{
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
	}
	 
	public boolean deleteDept(Dept d){
		return deptService.deleteDept(d);
	}

	public List<Dept> findByDname(String name){
		return deptService.findByDname(name);
	}
	
}
